<!DOCTYPE html>
<html>

<head>
  <title>Quarkus - Introduction to Contexts and Dependency Injection</title>
  <script id="adobe_dtm" src="https://www.redhat.com/dtm.js" type="text/javascript"></script>
  <script src="/assets/javascript/highlight.pack.js" type="text/javascript"></script>
  <META HTTP-EQUIV='Content-Security-Policy' CONTENT="default-src 'none'; script-src 'self' 'unsafe-eval' 'sha256-ANpuoVzuSex6VhqpYgsG25OHWVA1I+F6aGU04LoI+5s=' 'sha256-ipy9P/3rZZW06mTLAR0EnXvxSNcnfSDPLDuh3kzbB1w=' js.bizographics.com https://www.redhat.com assets.adobedtm.com jsonip.com https://ajax.googleapis.com https://www.googletagmanager.com https://www.google-analytics.com https://use.fontawesome.com; style-src 'self' https://fonts.googleapis.com https://use.fontawesome.com; img-src 'self' *; media-src 'self' ; frame-src https://www.googletagmanager.com https://www.youtube.com; frame-ancestors 'none'; base-uri 'none'; object-src 'none'; form-action 'none'; font-src 'self' https://use.fontawesome.com https://fonts.gstatic.com;">
  <META HTTP-EQUIV='X-Frame-Options' CONTENT="DENY">
  <META HTTP-EQUIV='X-XSS-Protection' CONTENT="1; mode=block">
  <META HTTP-EQUIV='X-Content-Type-Options' CONTENT="nosniff">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="Quarkus: Supersonic Subatomic Java">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:site" content="@QuarkusIO"> 
  <meta name="twitter:creator" content="@QuarkusIO">
  <meta property="og:url" content="https://quarkus.io/guides/cdi" />
  <meta property="og:title" content="Quarkus - Introduction to Contexts and Dependency Injection" />
  <meta property="og:description" content="Quarkus: Supersonic Subatomic Java" />
  <meta property="og:image" content="/assets/images/quarkus_card.png" />
  <link rel="canonical" href="https://quarkus.io/guides/cdi">
  <link rel="shortcut icon" type="image/png" href="/favicon.ico" >
  <link rel="stylesheet" href="https://quarkus.io/guides/stylesheet/config.css" />
  <link rel="stylesheet" href="/assets/css/main.css" />
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
  <link rel="alternate" type="application/rss+xml"  href="https://quarkus.io/feed.xml" title="Quarkus">
  <script src="https://quarkus.io/assets/javascript/goan.js" type="text/javascript"></script>
  <script src="https://quarkus.io/assets/javascript/hl.js" type="text/javascript"></script>
</head>

<body class="guides">
  <!-- Google Tag Manager (noscript) -->
  <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-NJWS5L"
  height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
  <!-- End Google Tag Manager (noscript) -->

  <div class="nav-wrapper">
  <div class="grid-wrapper">
    <div class="width-12-12">
      <input type="checkbox" id="checkbox" />
      <nav id="main-nav" class="main-nav">
  <div class="container">
    <div class="logo-wrapper">
      
        <a href="/"><img src="/assets/images/quarkus_logo_horizontal_rgb_600px_reverse.png" class="project-logo" title="Quarkus"></a>
      
    </div>
    <label class="nav-toggle" for="checkbox">
      <i class="fa fa-bars"></i>
    </label>
    <div id="menu" class="menu">
      <span>
        <a href="/get-started/" class="">Get Started</a>
      </span>
      <span>
        <a href="/guides/" class="active">Guides</a>
      </span>
      <span>
        <a href="/community/" class="">Community</a>
      </span>
      <span>
        <a href="/support/" class="">Support</a>
      </span>
      <span>
        <a href="/blog/" class="">Blog</a>
      </span>
      <span>
        <a href="https://code.quarkus.io" class="button-cta secondary white">Start Coding</a>
      </span>
    </div>
  </div>
      </nav>
    </div>
  </div>
</div>

  <div class="content">
    <div class="guide">
  <div class="width-12-12">
    <h1 class="text-caps">Quarkus - Introduction to Contexts and Dependency Injection</h1>
    <div class="hide-mobile toc"><ul class="sectlevel1">
<li><a href="#q-ok-lets-start-simple-what-is-a-bean">1. <em>Q: OK. Let&#8217;s start simple. What is a bean?</em></a></li>
<li><a href="#q-wait-a-minute-what-does-container-managed-mean">2. <em>Q: Wait a minute. What does "container-managed" mean?</em></a></li>
<li><a href="#q-what-is-it-good-for">3. <em>Q: What is it good for?</em></a></li>
<li><a href="#q-what-does-a-bean-look-like">4. <em>Q: What does a bean look like?</em></a></li>
<li><a href="#q-nice-how-does-the-dependency-resolution-work-i-see-no-names-or-identifiers">5. <em>Q: Nice. How does the dependency resolution work? I see no names or identifiers.</em></a></li>
<li><a href="#q-hm-wait-a-minute-what-happens-if-multiple-beans-declare-the-same-type">6. <em>Q: Hm, wait a minute. What happens if multiple beans declare the same type?</em></a></li>
<li><a href="#q-can-i-use-setter-and-constructor-injection">7. <em>Q: Can I use setter and constructor injection?</em></a></li>
<li><a href="#q-you-talked-about-some-qualifiers">8. <em>Q: You talked about some qualifiers?</em></a></li>
<li><a href="#q-looks-good-what-is-the-bean-scope">9. <em>Q: Looks good. What is the bean scope?</em></a></li>
<li><a href="#q-what-scopes-can-i-actually-use-in-my-quarkus-application">10. <em>Q: What scopes can I actually use in my Quarkus application?</em></a></li>
<li><a href="#client_proxies">11. <em>Q: I don&#8217;t undestand the concept of client proxies.</em></a></li>
<li><a href="#q-ok-you-said-that-there-are-several-kinds-of-beans">12. <em>Q: OK. You said that there are several kinds of beans?</em></a></li>
<li><a href="#q-ok-injection-looks-cool-what-other-services-are-provided">13. <em>Q: OK, injection looks cool. What other services are provided?</em></a>
<ul class="sectlevel2">
<li><a href="#lifecycle-callbacks">13.1. Lifecycle Callbacks</a></li>
<li><a href="#interceptors">13.2. Interceptors</a></li>
<li><a href="#events-and-observers">13.3. Events and Observers</a></li>
</ul>
</li>
<li><a href="#conclusion">14. Conclusion</a></li>
</ul></div>
    <div>
      <div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>In this guide we&#8217;re going to describe the basic principles of the Quarkus programming model that is based on the <a href="http://docs.jboss.org/cdi/spec/2.0/cdi-spec.html" target="_blank" rel="noopener">Contexts and Dependency Injection for Java 2.0</a> specification.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="q-ok-lets-start-simple-what-is-a-bean"><a class="anchor" href="#q-ok-lets-start-simple-what-is-a-bean"></a>1. <em>Q: OK. Let&#8217;s start simple. What is a bean?</em></h2>
<div class="sectionbody">
<div class="paragraph">
<p>A: Well, a bean is a <em>container-managed</em> object that supports a set of basic services, such as injection of dependencies, lifecycle callbacks and interceptors.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="q-wait-a-minute-what-does-container-managed-mean"><a class="anchor" href="#q-wait-a-minute-what-does-container-managed-mean"></a>2. <em>Q: Wait a minute. What does "container-managed" mean?</em></h2>
<div class="sectionbody">
<div class="paragraph">
<p>A: Simply put, you don&#8217;t control the lifecycle of the object instance directly.
Instead, you can affect the lifecycle through declarative means, such as annotations, configuration, etc.
The container is the <em>environment</em> where your application runs.
It creates and destroys the instances of beans, associates the instances with a designated context, and injects them into other beans.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="q-what-is-it-good-for"><a class="anchor" href="#q-what-is-it-good-for"></a>3. <em>Q: What is it good for?</em></h2>
<div class="sectionbody">
<div class="paragraph">
<p>A: An application developer can focus on the business logic rather than finding out "where and how" to obtain a fully initialized component with all of its dependencies.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
You&#8217;ve probably heard of the <em>inversion of control</em> (IoC) programming principle. Dependency injection is one of the implementation techniques of IoC.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="q-what-does-a-bean-look-like"><a class="anchor" href="#q-what-does-a-bean-look-like"></a>4. <em>Q: What does a bean look like?</em></h2>
<div class="sectionbody">
<div class="paragraph">
<p>A: There are several kinds of beans.
The most common ones are class-based beans:</p>
</div>
<div class="listingblock">
<div class="title">Simple Bean Example</div>
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">import javax.inject.Inject;
import javax.enterprise.context.ApplicationScoped;
import org.eclipse.microprofile.metrics.annotation.Counted;

@ApplicationScoped <i class="conum" data-value="1"></i><b>(1)</b>
public class Translator {

    @Inject
    Dictionary dictionary; <i class="conum" data-value="2"></i><b>(2)</b>

    @Counted  <i class="conum" data-value="3"></i><b>(3)</b>
    String translate(String sentence) {
      // ...
    }
}</code></pre>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td>This is a scope annotation. It tells the container which context to associate the bean instance with. In this particular case, a <strong>single bean instance</strong> is created for the application and used by all other beans that inject <code>Translator</code>.</td>
</tr>
<tr>
<td><i class="conum" data-value="2"></i><b>2</b></td>
<td>This is a field injection point. It tells the container that <code>Translator</code> depends on the <code>Dictionary</code> bean. If there is no matching bean the build fails.</td>
</tr>
<tr>
<td><i class="conum" data-value="3"></i><b>3</b></td>
<td>This is an interceptor binding annotation. In this case, the annotation comes from the MicroProfile Metrics. The relevant interceptor intercepts the invocation and updates the relevant metrics. We will about <a href="#interceptors">interceptors</a> later.</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="q-nice-how-does-the-dependency-resolution-work-i-see-no-names-or-identifiers"><a class="anchor" href="#q-nice-how-does-the-dependency-resolution-work-i-see-no-names-or-identifiers"></a>5. <em>Q: Nice. How does the dependency resolution work? I see no names or identifiers.</em></h2>
<div class="sectionbody">
<div class="paragraph">
<p>A: That&#8217;s a good question.
In CDI the process of matching a bean to an injection point is <strong>type-safe</strong>.
Each bean declares a set of bean types.
In our example above, the <code>Translator</code> bean has two bean types: <code>Translator</code> and <code>java.lang.Object</code>.
Subsequently, a bean is assignable to an injection point if the bean has a bean type that matches the <em>required type</em> and has all the <em>required qualifiers</em>.
We&#8217;ll talk about qualifiers later.
For now, it&#8217;s enough to know that the bean above is assignable to an injection point of type <code>Translator</code> and <code>java.lang.Object</code>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="q-hm-wait-a-minute-what-happens-if-multiple-beans-declare-the-same-type"><a class="anchor" href="#q-hm-wait-a-minute-what-happens-if-multiple-beans-declare-the-same-type"></a>6. <em>Q: Hm, wait a minute. What happens if multiple beans declare the same type?</em></h2>
<div class="sectionbody">
<div class="paragraph">
<p>A: There is a simple rule: <strong>exactly one bean must be assignable to an injection point, otherwise the build fails</strong>.
If none is assignable the build fails with <code>UnsatisfiedResolutionException</code>.
If multiple are assignable the build fails with <code>AmbiguousResolutionException</code>.
This is very useful because your application fails fast whenever the container is not able to find an unambiguous dependency for any injection point.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Your can use programmatic lookup via  <code>javax.enterprise.inject.Instance</code> to resolve ambiguities at runtime and even iterate over all beans implementing a given type:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">public class Translator {

    @Inject
    Instance&lt;Dictionary&gt; dictionaries; <i class="conum" data-value="1"></i><b>(1)</b>

    String translate(String sentence) {
      for (Dictionary dict : dictionaries) { <i class="conum" data-value="2"></i><b>(2)</b>
         // ...
      }
    }
}</code></pre>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td>This injection point will not result in an ambiguous dependency even if there are multiple beans that implement the <code>Dictionary</code> type.</td>
</tr>
<tr>
<td><i class="conum" data-value="2"></i><b>2</b></td>
<td><code>javax.enterprise.inject.Instance</code> extends <code>Iterable</code>.</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="q-can-i-use-setter-and-constructor-injection"><a class="anchor" href="#q-can-i-use-setter-and-constructor-injection"></a>7. <em>Q: Can I use setter and constructor injection?</em></h2>
<div class="sectionbody">
<div class="paragraph">
<p>A: Yes, you can.
In fact, in CDI the "setter injection" is superseded by more powerful <a href="https://docs.jboss.org/cdi/spec/2.0/cdi-spec.html#initializer_methods" target="_blank" rel="noopener">initializer methods</a>.
Intializers may accept multiple parameters and don&#8217;t have to follow the JavaBean naming conventions.</p>
</div>
<div class="listingblock">
<div class="title">Initialized and Constructor Injection Example</div>
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">@ApplicationScoped
public class Translator {

    private final TranslatorHelper helper

    Translator(TranslatorHelper helper) { <i class="conum" data-value="1"></i><b>(1)</b>
       this.helper = helper;
    }

    @Inject <i class="conum" data-value="2"></i><b>(2)</b>
    void setDeps(Dictionary dic, LocalizationService locService) { <i class="conum" data-value="3"></i><b>(3)</b>
      / ...
    }
}</code></pre>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td>This is a constructor injection.
In fact, this code would not work in regular CDI implementations where a bean with a normal scope must always declare a no-args constructor and the bean constructor must be annotated with <code>@Inject</code>.
However, in Quarkus we detect the absence of no-args constructor and "add" it directly in the bytecode.
It&#8217;s also not necessary to add <code>@Inject</code> if there is only one constructor present.</td>
</tr>
<tr>
<td><i class="conum" data-value="2"></i><b>2</b></td>
<td>An initializer method must be annotated with <code>@Inject</code>.</td>
</tr>
<tr>
<td><i class="conum" data-value="3"></i><b>3</b></td>
<td>An initializer may accept multiple parameters - each one is an injection point.</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="q-you-talked-about-some-qualifiers"><a class="anchor" href="#q-you-talked-about-some-qualifiers"></a>8. <em>Q: You talked about some qualifiers?</em></h2>
<div class="sectionbody">
<div class="paragraph">
<p>A: <a href="https://docs.jboss.org/cdi/spec/2.0/cdi-spec.html#qualifiers" target="_blank" rel="noopener">Qualifiers</a> are annotations that help the container to distinguish beans that implement the same type.
As we already said a bean is assignable to an injection point if it has all the required qualifiers.
If you declare no qualifier at an injection point the <code>@Default</code> qualifier is assumed.</p>
</div>
<div class="paragraph">
<p>A qualifier type is a Java annotation defined as <code>@Retention(RUNTIME)</code> and annotated with the <code>@javax.inject.Qualifier</code> meta-annotation:</p>
</div>
<div class="listingblock">
<div class="title">Qualifier Example</div>
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface Superior {}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The qualifiers of a bean are declared by annotating the bean class or producer method or field with the qualifier types:</p>
</div>
<div class="listingblock">
<div class="title">Bean With Custom Qualifier Example</div>
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">@Superior <i class="conum" data-value="1"></i><b>(1)</b>
@ApplicationScoped
public class SuperiorTranslator extends Translator {

    String translate(String sentence) {
      // ...
    }
}</code></pre>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td><code>@Superior</code> is a <a href="https://docs.jboss.org/cdi/spec/2.0/cdi-spec.html#defining_qualifier_types" target="_blank" rel="noopener">qualifier annotation</a>.</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>This bean would be assignable to <code>@Inject @Superior Translator</code> and <code>@Inject @Superior SuperiorTranslator</code> but not to <code>@Inject Translator</code>.
The reason is that <code>@Inject Translator</code> is automatically transformed to <code>@Inject @Default Translator</code> during typesafe resolution.
And since our <code>SuperiorTranslator</code> does not declare <code>@Default</code> only the original <code>Translator</code> bean is assignable.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="q-looks-good-what-is-the-bean-scope"><a class="anchor" href="#q-looks-good-what-is-the-bean-scope"></a>9. <em>Q: Looks good. What is the bean scope?</em></h2>
<div class="sectionbody">
<div class="paragraph">
<p>The scope of a bean determines the lifecycle of its instances, i.e. when and where an instance should be created and destroyed.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Every bean has exactly one scope.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="q-what-scopes-can-i-actually-use-in-my-quarkus-application"><a class="anchor" href="#q-what-scopes-can-i-actually-use-in-my-quarkus-application"></a>10. <em>Q: What scopes can I actually use in my Quarkus application?</em></h2>
<div class="sectionbody">
<div class="paragraph">
<p>A: You can use all the built-in scopes mentioned by the specification except for <code>javax.enterprise.context.ConversationScoped</code>.</p>
</div>
<table class="tableblock frame-all grid-all stretch">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Annotation</th>
<th class="tableblock halign-left valign-top">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>@javax.enterprise.context.ApplicationScoped</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">A single bean instance is used for the application and shared among all injection points. The instance is created lazily, i.e. once a method is invoked upon the <a href="#client_proxies">client proxy</a>.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>@javax.inject.Singleton</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Just like <code>@ApplicationScoped</code> except that no client proxy is used. The instance is created when an injection point that resolves to a @Singleton bean is being injected.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>@javax.enterprise.context.RequestScoped</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">The bean instance is associated with the current <em>request</em> (usually an HTTP request).</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>@javax.enterprise.context.Dependent</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">This is a pseudo-scope. The instances are not shared and every injection point spawns a new instance of the dependent bean. The lifecycle of dependent bean is bound to the bean injecting it - it will be created and destroyed along with the bean injecting it.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>@javax.enterprise.context.SessionScoped</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">This scope is backed by an <code>javax.servlet.http.HttpSession</code> object. It&#8217;s only available if the <code>quarkus-undertow</code> extension is used.</p></td>
</tr>
</tbody>
</table>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
There can be other custom scopes provided by Quarkus extensions. For example, <code>quarkus-narayana-jta</code> provides <code>javax.transaction.TransactionScoped</code>.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="client_proxies"><a class="anchor" href="#client_proxies"></a>11. <em>Q: I don&#8217;t undestand the concept of client proxies.</em></h2>
<div class="sectionbody">
<div class="paragraph">
<p>Indeed, the <a href="https://docs.jboss.org/cdi/spec/2.0/cdi-spec.html#client_proxies" target="_blank" rel="noopener">client proxies</a> could be hard to grasp but they provide some useful functionality.
A client proxy is basically an object that delegates all method invocations to a target bean instance.
It&#8217;s a container construct that implements <code>io.quarkus.arc.ClientProxy</code> and extends the bean class.</p>
</div>
<div class="listingblock">
<div class="title">Generated Client Proxy Example</div>
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">@ApplicationScoped
class Translator {

    String translate(String sentence) {
      // ...
    }
}

// The client proxy class is generated and looks like...
class Translator_ClientProxy extends Translator { <i class="conum" data-value="1"></i><b>(1)</b>

    String translate(String sentence) {
      // Find the correct translator instance...
      Translator translator = getTranslatorInstanceFromTheApplicationContext();
      // And delegate the method invocation...
      return translator.translate(sentence);
    }
}</code></pre>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td>The <code>Translator_ClientProxy</code> instance is always injected instead of a direct reference to a <a href="https://docs.jboss.org/cdi/spec/2.0/cdi-spec.html#contextual_instance" target="_blank" rel="noopener">contextual instance</a> of the <code>Translator</code> bean.</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Client proxies allow for:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Lazy instantiation - the instance is created once a method is invoked upon the proxy.</p>
</li>
<li>
<p>Ability to inject a bean with "narrower" scope to a bean with "wider" scope; i.e. you can inject a <code>@RequestScoped</code> bean into an <code>@ApplicationScoped</code> bean.</p>
</li>
<li>
<p>Circular dependencies in the dependency graph. Having circular dependencies is often an indication that a redesign should be considered, but sometimes it&#8217;s inevitable.</p>
</li>
<li>
<p>In rare cases it&#8217;s practical to destroy the beans manually. A direct injected reference would lead to a stale bean instance.</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1">
<h2 id="q-ok-you-said-that-there-are-several-kinds-of-beans"><a class="anchor" href="#q-ok-you-said-that-there-are-several-kinds-of-beans"></a>12. <em>Q: OK. You said that there are several kinds of beans?</em></h2>
<div class="sectionbody">
<div class="paragraph">
<p>A: Yes. In general, we distinguish:</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Class beans</p>
</li>
<li>
<p>Producer methods</p>
</li>
<li>
<p>Producer fields</p>
</li>
<li>
<p>Synthetic beans</p>
</li>
</ol>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Synthetic beans are usually provided by extensions. Therefore, we not going to cover them in this guide.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Producer methods and fields are useful if you need additional control over instantiation of a bean.
They are also useful when integrating third-party libraries where you don&#8217;t control the class source and may not add additional annotations etc.</p>
</div>
<div class="listingblock">
<div class="title">Producers Example</div>
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">@ApplicationScoped
public class Producers {

    @Produces <i class="conum" data-value="1"></i><b>(1)</b>
    double pi = Math.PI; <i class="conum" data-value="2"></i><b>(2)</b>

    @Produces <i class="conum" data-value="3"></i><b>(3)</b>
    List&lt;String&gt; names() {
       List&lt;String&gt; names = new ArrayList&lt;&gt;();
       names.add("Andy");
       names.add("Adalbert");
       names.add("Joachim");
       return names; <i class="conum" data-value="4"></i><b>(4)</b>
    }
}

@ApplicationScoped
public class Consumer {

   @Inject
   double pi;

   @Inject
   List&lt;String&gt; names;

   // ...
}</code></pre>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td>The container analyses the field annotations to build a bean metadata.
The <em>type</em> is used to build the set of bean types.
In this case, it will be <code>double</code> and <code>java.lang.Object</code>.
No scope annotation is declared and so it&#8217;s defaulted to <code>@Dependent</code>.</td>
</tr>
<tr>
<td><i class="conum" data-value="2"></i><b>2</b></td>
<td>The container will read this field when creating the bean instance.</td>
</tr>
<tr>
<td><i class="conum" data-value="3"></i><b>3</b></td>
<td>The container analyses the method annotations to build a bean metadata.
The <em>return type</em> is used to build the set of bean types.
In this case, it will be <code>List&lt;String&gt;</code>, <code>Collection&lt;String&gt;</code>, <code>Iterable&lt;String&gt;</code> and <code>java.lang.Object</code>.
No scope annotation is declared and so it&#8217;s defaulted to <code>@Dependent</code>.</td>
</tr>
<tr>
<td><i class="conum" data-value="4"></i><b>4</b></td>
<td>The container will call this method when creating the bean instance.</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>There&#8217;s more about producers.
You can declare qualifiers, inject dependencies into the producer methods parameters, etc.
You can read more about producers for example in the <a href="https://docs.jboss.org/weld/reference/latest/en-US/html/beanscdi.html#_producer_methods" target="_blank" rel="noopener">Weld docs</a>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="q-ok-injection-looks-cool-what-other-services-are-provided"><a class="anchor" href="#q-ok-injection-looks-cool-what-other-services-are-provided"></a>13. <em>Q: OK, injection looks cool. What other services are provided?</em></h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="lifecycle-callbacks"><a class="anchor" href="#lifecycle-callbacks"></a>13.1. Lifecycle Callbacks</h3>
<div class="paragraph">
<p>A bean class may declare lifecycle <code>@PostConstruct</code> and <code>@PreDestroy</code> callbacks:</p>
</div>
<div class="listingblock">
<div class="title">Lifecycle Callbacks Example</div>
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@ApplicationScoped
public class Translator {

    @PostConstruct <i class="conum" data-value="1"></i><b>(1)</b>
    void init() {
       // ...
    }

    @PreDestroy <i class="conum" data-value="2"></i><b>(2)</b>
    void destroy() {
      // ...
    }
}</code></pre>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td>This callback is invoked before the bean instance is put into service. It is safe to perform some initialization here.</td>
</tr>
<tr>
<td><i class="conum" data-value="2"></i><b>2</b></td>
<td>This callback is invoked before the bean instance is destroyed. It is safe to perform some cleanup tasks here.</td>
</tr>
</table>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
It&#8217;s a good practice to keep the logic in the callbacks "without side effects", i.e. you should avoid calling other beans inside the callbacks.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="interceptors"><a class="anchor" href="#interceptors"></a>13.2. Interceptors</h3>
<div class="paragraph">
<p>Interceptors are used to separate cross-cutting concerns from business logic.
There is a separate specification - Java Interceptors - that defines the basic programming model and semantics.</p>
</div>
<div class="listingblock">
<div class="title">Simple Interceptor Example</div>
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">import javax.interceptor.Interceptor;
import javax.annotation.Priority;

@Logged <i class="conum" data-value="1"></i><b>(1)</b>
@Priority(2020) <i class="conum" data-value="2"></i><b>(2)</b>
@Interceptor <i class="conum" data-value="3"></i><b>(3)</b>
public class LoggingInterceptor {

   @Inject <i class="conum" data-value="4"></i><b>(4)</b>
   Logger logger;

   @AroundInvoke <i class="conum" data-value="5"></i><b>(5)</b>
   Objec logInvocation(InvocationContext context) {
      // ...log before
      Objec ret = context.proceed(); <i class="conum" data-value="6"></i><b>(6)</b>
      // ...log after
      return ret;
   }

}</code></pre>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td>This is an interceptor binding annotation that is used to bind our interceptor to a bean. Simply annotate a bean class with <code>@Logged</code>.</td>
</tr>
<tr>
<td><i class="conum" data-value="2"></i><b>2</b></td>
<td><code>Priority</code> enables the interceptor and affects the interceptor ordering. Interceptors with smaller priority values are called first.</td>
</tr>
<tr>
<td><i class="conum" data-value="3"></i><b>3</b></td>
<td>Marks an interceptor component.</td>
</tr>
<tr>
<td><i class="conum" data-value="4"></i><b>4</b></td>
<td>An interceptor instance may be the target of dependency injection.</td>
</tr>
<tr>
<td><i class="conum" data-value="5"></i><b>5</b></td>
<td><code>AroundInvoke</code> denotes a method that interposes on business methods.</td>
</tr>
<tr>
<td><i class="conum" data-value="6"></i><b>6</b></td>
<td>Proceed to the next interceptor in the interceptor chain or invoke the intercepted business method.</td>
</tr>
</table>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Instances of interceptors are dependent objects of the bean instance they intercept, i.e. a new interceptor instance is created for each intercepted bean.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="events-and-observers"><a class="anchor" href="#events-and-observers"></a>13.3. Events and Observers</h3>
<div class="paragraph">
<p>Beans may also produce and consume events to interact in a completely decoupled fashion.
Any Java object can serve as an event payload.
The optional qualifiers act as topic selectors.</p>
</div>
<div class="listingblock">
<div class="title">Simple Event Example</div>
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">class TaskCompleted {
  // ...
}

@ApplicationScoped
class ComplicatedService {

   @Inject
   Event&lt;Task&gt; event; <i class="conum" data-value="1"></i><b>(1)</b>

   void doSomething() {
      // ...
      event.fire(new TaskCompleted()); <i class="conum" data-value="2"></i><b>(2)</b>
   }

}

@ApplicationScoped
class Logger {

   void onTaskCompleted(@Observes TaskCompleted task) { <i class="conum" data-value="3"></i><b>(3)</b>
      // ...log the task
   }

}</code></pre>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td><code>javax.enterprise.event.Event</code> is used to fire events.</td>
</tr>
<tr>
<td><i class="conum" data-value="2"></i><b>2</b></td>
<td>Fire the event synchronously.</td>
</tr>
<tr>
<td><i class="conum" data-value="3"></i><b>3</b></td>
<td>This method is notified when a <code>TaskCompleted</code> event is fired.</td>
</tr>
</table>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
For more info about events/observers visit <a href="https://docs.jboss.org/weld/reference/latest/en-US/html/events.html" target="_blank" rel="noopener">Weld docs</a>.
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="conclusion"><a class="anchor" href="#conclusion"></a>14. Conclusion</h2>
<div class="sectionbody">
<div class="paragraph">
<p>In this guide, we&#8217;ve covered some of the basic topics of the Quarkus programming model that is based on the <a href="http://docs.jboss.org/cdi/spec/2.0/cdi-spec.html" target="_blank" rel="noopener">Contexts and Dependency Injection for Java 2.0</a> specification.
However, a full CDI implementation is not used under the hood.
Quarkus only implements a subset of the CDI features - see also <a href="cdi-reference#supported_features">the list of supported features</a> and <a href="cdi-reference#limitations">the list of limitations</a>.
On the other hand, there are quite a few <a href="cdi-reference#nonstandard_features">non-standard features</a> and <a href="cdi-reference#build_time_apis">Quarkus-specific APIs</a>.
We believe that our efforts will drive the innovation of the CDI specification towards the build-time oriented developer stacks in the future.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
If you wish to learn more about Quarkus-specific features and limitations there is a Quarkus <a href="cdi-reference">CDI Reference Guide</a>.
We also recommend you to read the <a href="http://docs.jboss.org/cdi/spec/2.0/cdi-spec.html">CDI specification</a> and the <a href="https://docs.jboss.org/weld/reference/latest/en-US/html/">Weld documentation</a> (Weld is a CDI Reference Implementation) to get acquainted with more complex topics.
</td>
</tr>
</table>
</div>
</div>
</div>
    </div>
  </div>
</div>

  </div>

  <div class="content project-footer">
  <div class="footer-section">
    <div class="logo-wrapper">
      <a href="/"><img src="/assets/images/quarkus_logo_horizontal_rgb_reverse.svg" class="project-logo" title="Quarkus"></a>
    </div>
  </div>
  <div class="grid-wrapper">
    <p class="grid__item width-3-12">Quarkus is open. All dependencies of this project are available under the <a href='https://www.apache.org/licenses/LICENSE-2.0' target='_blank'>Apache Software License 2.0</a> or compatible license.<br /><br />This website was built with <a href='https://jekyllrb.com/' target='_blank'>Jekyll</a>, is hosted on <a href='https://pages.github.com/' target='_blank'>Github Pages</a> and is completely open source. If you want to make it better, <a href='https://github.com/quarkusio/quarkusio.github.io' target='_blank'>fork the website</a> and show us what you’ve got.</p>

    
      <div class="width-1-12 project-links">
        <span>Navigation</span>
        <ul class="footer-links width-1-12">
          
            <li><a href="/">Home</a></li>
          
            <li><a href="/guides">Guides</a></li>
          
            <li><a href="/community/#contributing">Contribute</a></li>
          
            <li><a href="/faq">FAQ</a></li>
          
            <li><a href="/get-started">Get Started</a></li>
          
        </ul>
      </div>
    
      <div class="width-1-12 project-links">
        <span>Contribute</span>
        <ul class="footer-links width-1-12">
          
            <li><a href="https://twitter.com/quarkusio">Follow us</a></li>
          
            <li><a href="https://github.com/quarkusio">GitHub</a></li>
          
            <li><a href="/security">Security&nbsp;policy</a></li>
          
        </ul>
      </div>
    
      <div class="width-1-12 project-links">
        <span>Get Help</span>
        <ul class="footer-links width-1-12">
          
            <li><a href="https://groups.google.com/forum/#!forum/quarkus-dev">Forums</a></li>
          
            <li><a href="https://quarkusio.zulipchat.com">Chatroom</a></li>
          
        </ul>
      </div>
    

    
      <div class="width-3-12 more-links">
        <span>Quarkus is made of community projects</span>
        <ul class="footer-links">
          
            <li><a href="https://vertx.io/" target="_blank">Eclipse Vert.x</a></li>
          
            <li><a href="https://microprofile.io" target="_blank">Eclipse MicroProfile</a></li>
          
            <li><a href="https://hibernate.org" target="_blank">Hibernate</a></li>
          
            <li><a href="https://netty.io" target="_blank">Netty</a></li>
          
            <li><a href="https://resteasy.github.io" target="_blank">RESTEasy</a></li>
          
            <li><a href="https://camel.apache.org" target="_blank">Apache Camel</a></li>
          
            <li><a href="https://code.quarkus.io/" target="_blank">And many more...</a></li>
          
        </ul>
      </div>
    
  </div>
</div>
  <div class="content redhat-footer">
  <div class="grid-wrapper">
    <span class="licence">
      <i class="fab fa-creative-commons"></i><i class="fab fa-creative-commons-by"></i> <a href="https://creativecommons.org/licenses/by/3.0/" target="_blank">CC by 3.0</a> | <a href="https://www.redhat.com/en/about/privacy-policy">Privacy Policy</a>
    </span>
    <span class="redhat">
      Sponsored by
    </span>
    <span class="redhat-logo">
      <a href="https://www.redhat.com/" target="_blank"><img src="/assets/images/redhat_reversed.svg"></a>
    </span>
  </div>
</div>


  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" integrity="sha384-8gBf6Y4YYq7Jx97PIqmTwLPin4hxIzQw5aDmUg/DDhul9fFpbbLcLh3nTIIDJKhx" crossorigin="anonymous"></script>
  <script type="text/javascript" src="/assets/javascript/mobile-nav.js"></script>
  <script type="text/javascript" src="/assets/javascript/scroll-down.js"></script>
  <script src="/assets/javascript/satellite.js" type="text/javascript"></script>
  <script src="https://quarkus.io/guides/javascript/config.js" type="text/javascript"></script>
  <script src="/assets/javascript/search-filter.js" type="text/javascript"></script>
  <script src="/assets/javascript/back-to-top.js" type="text/javascript"></script>
</body>

</html>
